﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CuaHangBangDia;
using System.Collections;
using CuaHangBangDia.Home;

namespace CuaHangBangDia.QLHoaDon
{
    public partial class ThemHoaDonForm : Form
    {
        public static int mahoadoncanin = 0;
        public int mahoadon;
        public double tien;
        public static string nvlap;
        public ThemHoaDonForm()
        {
            InitializeComponent();
        }



        private void dgvThemChiTietHoaDon_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridViewRow r = dgvThemChiTietHoaDon.CurrentRow;
            TextBox txt = e.Control as TextBox;
            if (e.Control is TextBox && dgvThemChiTietHoaDon.CurrentCell.ColumnIndex == dgvThemChiTietHoaDon.Columns["TenBangDia"].Index)
            {
                for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count; i++)
                {

                    txt.Multiline = false;
                    txt.AutoCompleteCustomSource = new AutoCompleteStringCollection();
                    List<BangDia> li = BangDia.Objects.GetAll().ToList();
                    foreach (BangDia item in li)
                    {
                        txt.AutoCompleteCustomSource.Add(item.TenBangDia);
                    }
                    txt.AutoCompleteMode = AutoCompleteMode.Suggest;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
            else
            {
                txt.AutoCompleteMode = AutoCompleteMode.None;
                txt.AutoCompleteSource = AutoCompleteSource.None;
            }
        }

        private void btnThemChiTetHoaDon_Click(object sender, EventArgs e)
        {

            if (dgvThemChiTietHoaDon.Rows.Count - 1 > 0)
            {
                lblSoTienBangChu.Text = DinhDang(ChuyenSo(lblTongTien.Text)) + " Đồng";
                btnIn.Enabled = true;
                int mahd = 0;
                double tien1 = 0;
                int mabd = 0;
                bool tb = false;
                bool kqthem = false;

                HoaDon hd = getDataHoaDon();
                HoaDon.Objects.Add(hd);
                for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count - 1; i++)
                {

                    ChiTietHoaDon cthd = new ChiTietHoaDon();
                    DateTime t = hd.NgayLap;
                    List<HoaDon> l = HoaDon.Objects.Find(m => m.NgayLap == t).ToList();
                    foreach (HoaDon item in l)
                    {
                        mahd = item.MaHoaDon;
                        tien1 = item.ThanhTien;

                    }
                    mahoadoncanin = mahd;
                    tien = tien1;
                    string ten = dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString();
                    List<BangDia> lbd = BangDia.Objects.Find(bd => bd.TenBangDia == ten).ToList();
                    foreach (BangDia item in lbd)
                    {

                        mabd = item.MaBangDia;
                    }
                    cthd.MaHoaDon = mahd;
                    cthd.MaBangDia = mabd;
                    cthd.SoLuongBan = Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[2].Value);
                    cthd.TenBangDia = ten;
                    cthd.Tien = Convert.ToDouble(dgvThemChiTietHoaDon.Rows[i].Cells[3].Value);
                    bool h = ChiTietHoaDon.Objects.Insert(cthd);
                    if (h == true)
                    {
                        kqthem = true;
                    }
                    else
                    {
                        kqthem = false;
                    }
                    BangDia bds = new BangDia();
                    int sl = Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[3].Value);
                    bool kq = false;
                    List<BangDia> list = LayBangDia();

                    if (list.Count > 0)
                    {
                        foreach (BangDia item in list)
                        {
                            kq = BangDia.Objects.Update(item);
                        }
                        if (kq)
                        {
                            tb = true;

                        }
                        else
                        {
                            dgvThemChiTietHoaDon.Rows[i].Cells[0].Value = false;
                        }
                    }
                    else
                        MessageBox.Show("Vui lòng chọn chi tiết muốn Cập Nhật ");
                }
                DateTime d = DateTime.Now;
                List<BanHang> lk = BanHang.Objects.Find(m => (m.NgayBan.Day == d.Day && m.NgayBan.Month == d.Month && m.NgayBan.Year == d.Year)).ToList();
                if (lk.Count == 0)
                {
                    BanHang g = new BanHang();
                    g.NgayBan = d;
                    g.TienBan = Convert.ToDouble(lblTongTien.Text);
                    g.TienChoThue = 0;
                    g.KhacChi = 0;
                    g.KhacThu = 0;
                    g.Tong = Convert.ToDouble(lblTongTien.Text);
                    BanHang.Objects.Insert(g);
                }
                else
                {
                    BanHang bb = new BanHang();
                    foreach (BanHang item in lk)
                    {
                        bb.NgayBan = item.NgayBan;
                        bb.TienBan = item.TienBan + Convert.ToDouble(lblTongTien.Text);
                        bb.TienChoThue = item.TienChoThue;
                        bb.KhacChi = item.KhacChi;
                        bb.KhacThu = item.KhacThu;
                        bb.Tong = item.Tong + Convert.ToDouble(lblTongTien.Text);
                    }
                    BanHang.Objects.Update(bb);

                }
                if (kqthem == true)
                {

                    MessageBox.Show("Thêm hóa đơn thành công!", "Thông báo", MessageBoxButtons.OK,MessageBoxIcon.Information);
                    dgvThemChiTietHoaDon.Rows.Clear();
                    lblSoTienBangChu.Text = "Không Đồng";
                    lblTongTien.Text = "0";
                    dgvThemChiTietHoaDon.Rows[0].Cells[2].ReadOnly = true;
                    ThemHoaDon_ReportForm frm = new ThemHoaDon_ReportForm();
                    frm.mahoadon = mahoadoncanin;
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("Lỗi thêm hóa đơn!", "Lỗi",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Chưa nhập dữ liệu!", "Lỗi",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private List<BangDia> LayBangDia()
        {
            List<BangDia> list = new List<BangDia>();
            if (dgvThemChiTietHoaDon.Rows.Count > 0)
            {
                for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count; i++)
                {
                    try
                    {
                        if (dgvThemChiTietHoaDon.Rows[i].Cells[0].Value != null)
                        {
                            BangDia b = GetDataBangDia();
                            list.Add(b);
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            return list;
        }
        private BangDia GetDataBangDia()
        {
            int ma, sl;
            double gia;
            string ten, maloai, matl;
            BangDia sw = new BangDia();
            for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count - 1; i++)
            {

                string tb = dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString();
                List<BangDia> lbd = BangDia.Objects.Find(bd => bd.TenBangDia == tb).ToList();
                foreach (BangDia item in lbd)
                {
                    ma = item.MaBangDia;
                    ten = item.TenBangDia;
                    maloai = item.MaLoai;
                    matl = item.MaTheLoai;
                    gia = item.Gia;
                    sl = item.SoLuong;
                    sw.MaBangDia = ma;
                    sw.TenBangDia = ten;
                    sw.MaLoai = maloai;
                    sw.MaTheLoai = matl;
                    sw.Gia = gia;
                    sw.SoLuong = sl - Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[2].Value);

                }

            }



            return sw;
        }
        //Bắt lối khi nhập
        private void dgvThemChiTietHoaDon_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            btnIn.Enabled = false;
            int slbd = 0;
            double dem = 0;
            string tenbangdia = null;
            string tb = null;
            for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count - 1; i++)
            {
                if (dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString() == "")
                {
                    dgvThemChiTietHoaDon.Rows[i].Cells[2].ReadOnly = true;
                }
                else
                {
                    dgvThemChiTietHoaDon.Rows[i].Cells[2].ReadOnly = false;
                }

                tb = dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString();
                List<BangDia> lbd = BangDia.Objects.Find(bdia => bdia.TenBangDia == tb).ToList();

                if (lbd.Count == 0)
                {
                    MessageBox.Show("Băng đĩa '" + tb + "' không có trong danh sách băng đĩa!", "Lỗi",
                          MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dgvThemChiTietHoaDon.Rows.RemoveAt(i);
                    dgvThemChiTietHoaDon.Rows[i].Cells[2].ReadOnly = true;
                }
                foreach (BangDia item in lbd)
                {
                    slbd = item.SoLuong;
                }
                int sll = Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[2].Value);
                if (sll > slbd)
                {
                    MessageBox.Show("Số lượng đĩa '" + tb + "' trong kho không đủ! Chỉ còn lại " + slbd + " đĩa!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //dgvThemChiTietHoaDon.Rows.RemoveAt(i);
                    dgvThemChiTietHoaDon.Rows[i].Cells[0].Value = tb;
                    if (slbd > 0)
                    {
                        dgvThemChiTietHoaDon.Rows[i].Cells[2].Value = slbd;
                    }
                    else
                    {
                        dgvThemChiTietHoaDon.Rows.RemoveAt(i);
                    }

                    //dgvThemChiTietHoaDon.Rows[i].Cells[2].ReadOnly = false;
                }
                DataGridViewRow r = dgvThemChiTietHoaDon.CurrentRow;
                if (dgvThemChiTietHoaDon.Rows[i].Cells[0].Value != null)
                {
                    List<BangDia> j = BangDia.Objects.Find(p => p.TenBangDia == dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString()).ToList();
                    foreach (BangDia b in j)
                    {
                        dgvThemChiTietHoaDon.Rows[i].Cells[1].Value = b.Gia.ToString();
                    }

                }
                double dg = Convert.ToDouble(dgvThemChiTietHoaDon.Rows[i].Cells[1].Value);
                int sl = Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[2].Value);
                dgvThemChiTietHoaDon.Rows[i].Cells[3].Value = dg * sl;
                dem += Convert.ToDouble(dgvThemChiTietHoaDon.Rows[i].Cells[3].Value);
                lblTongTien.Text = dem.ToString();
                lblSoTienBangChu.Text = DinhDang(ChuyenSo(lblTongTien.Text)) + " Đồng";

                for (int jj = i + 1; jj < dgvThemChiTietHoaDon.Rows.Count - 1; jj++)
                {
                    if (dgvThemChiTietHoaDon.Rows[i].Cells[0].Value.ToString() == dgvThemChiTietHoaDon.Rows[jj].Cells[0].Value.ToString())
                    {
                        tenbangdia = dgvThemChiTietHoaDon.Rows[jj].Cells[0].Value.ToString();
                        MessageBox.Show("Băng đĩa '" + tenbangdia + "' đã có trong danh sách! Bạn hãy cập nhật lại số lượng cho băng đĩa này!", "Lỗi",
                          MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dgvThemChiTietHoaDon.Rows.RemoveAt(jj);
                        dgvThemChiTietHoaDon.Rows[jj].Cells[2].ReadOnly = true;
                    }

                }

            }

        }


        private HoaDon getDataHoaDon()
        {
            HoaDon hd = new HoaDon();
            hd.NgayLap = DateTime.Now;
            hd.ThanhTien = double.Parse(lblTongTien.Text);
            hd.NhanVienLap = nvlap;
            hd.SoTienBangChu = lblSoTienBangChu.Text;
            return hd;


        }

        private void btnThoatChiTietHoaDon_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnIn_Click(object sender, EventArgs e)
        {

            ThemHoaDon_ReportForm frm = new ThemHoaDon_ReportForm();
            frm.mahoadon = mahoadoncanin;
            frm.Show();
        }
        private string ChuyenSo(string number)
        {
            string[] dv = { "", "mươi", "trăm", "nghìn", "triệu", "tỉ" };
            string[] cs = { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string doc;
            int i, j, k, n, len, found, ddv, rd;

            len = number.Length;
            number += "ss";
            doc = "";
            found = 0;
            ddv = 0;
            rd = 0;

            i = 0;
            while (i < len)
            {
                //So chu so o hang dang duyet
                n = (len - i + 2) % 3 + 1;

                //Kiem tra so 0
                found = 0;
                for (j = 0; j < n; j++)
                {
                    if (number[i + j] != '0')
                    {
                        found = 1;
                        break;
                    }
                }

                //Duyet n chu so
                if (found == 1)
                {
                    rd = 1;
                    for (j = 0; j < n; j++)
                    {
                        ddv = 1;
                        switch (number[i + j])
                        {
                            case '0':
                                if (n - j == 3) doc += cs[0] + " ";
                                if (n - j == 2)
                                {
                                    if (number[i + j + 1] != '0') doc += "lẻ ";
                                    ddv = 0;
                                }
                                break;
                            case '1':
                                if (n - j == 3) doc += cs[1] + " ";
                                if (n - j == 2)
                                {
                                    doc += "mười ";
                                    ddv = 0;
                                }
                                if (n - j == 1)
                                {
                                    if (i + j == 0) k = 0;
                                    else k = i + j - 1;

                                    if (number[k] != '1' && number[k] != '0')
                                        doc += "mốt ";
                                    else
                                        doc += cs[1] + " ";
                                }
                                break;
                            case '5':
                                if (i + j == len - 1)
                                    doc += "lăm ";
                                else
                                    doc += cs[5] + " ";
                                break;
                            default:
                                doc += cs[(int)number[i + j] - 48] + " ";
                                break;
                        }

                        //Doc don vi nho
                        if (ddv == 1)
                        {
                            doc += dv[n - j - 1] + " ";
                        }
                    }
                }


                //Doc don vi lon
                if (len - i - n > 0)
                {
                    if ((len - i - n) % 9 == 0)
                    {
                        if (rd == 1)
                            for (k = 0; k < (len - i - n) / 9; k++)
                                doc += "tỉ ";
                        rd = 0;
                    }
                    else
                        if (found != 0) doc += dv[((len - i - n + 1) % 9) / 3 + 2] + " ";
                }

                i += n;
            }

            if (len == 1)
                if (number[0] == '0' || number[0] == '5') return cs[(int)number[0] - 48];

            return doc;
        }
        private string DinhDang(string s)
        {
            while (s[0] == ' ')
            {
                string temp = "";
                for (int i = 1; i < s.Length; i++)
                    temp += s[i];
                s = temp;
            }
            //while (s.IndexOf("  ") !=-1)
            //    s.Replace("  ", " ");

            string temp2 = "";
            temp2 += char.ToUpper(s[0]);
            for (int i = 1; i < s.Length; i++)
                temp2 += s[i];
            s = temp2;
            return s;
        }
        private void frmThemHoaDon_Load(object sender, EventArgs e)
        {
            btnIn.Enabled = false;

            lblSoTienBangChu.Text = "Không Đồng";
            lblTongTien.Text = "0";

        }

        private void dgvThemChiTietHoaDon_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            int newInteger;
            if (KT(e))
            {

                if ((!int.TryParse(e.FormattedValue.ToString(), out newInteger) 
                    && !String.IsNullOrWhiteSpace(e.FormattedValue.ToString()) || newInteger < 0 || newInteger > 100000))
                {
                    dgvThemChiTietHoaDon.Rows[e.RowIndex].ErrorText =
           "Số Lượng phải khác chuỗi";
                    e.Cancel = true;
                }
            }
        }
        private bool KT(DataGridViewCellValidatingEventArgs e)
        {
            if (dgvThemChiTietHoaDon.Columns[e.ColumnIndex].Name == "SoLuongBan")
                return true;
            return false;
        }

        private void dgvThemChiTietHoaDon_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            dgvThemChiTietHoaDon.Rows[e.RowIndex].ErrorText = "";
        }

        private void btnNhapLai_Click(object sender, EventArgs e)
        {
            dgvThemChiTietHoaDon.Rows.Clear();
            btnIn.Enabled = false;

            lblSoTienBangChu.Text = "Không Đồng";
            lblTongTien.Text = "0";
            dgvThemChiTietHoaDon.Rows[0].Cells[2].ReadOnly = true;
        }
        bool h;
        
        private void xóaDòngToolStripMenuItem_Click(object sender, EventArgs e)
        {

            int l = dgvThemChiTietHoaDon.CurrentRow.Index;
            if (dgvThemChiTietHoaDon.Rows[l].Cells[0].Value != null)
            {
                dgvThemChiTietHoaDon.Rows.RemoveAt(l);
                double dem1 = 0;
                for (int i = 0; i < dgvThemChiTietHoaDon.Rows.Count; i++)
                {
                    
                    double dg = Convert.ToDouble(dgvThemChiTietHoaDon.Rows[i].Cells[1].Value);
                    int sl = Convert.ToInt32(dgvThemChiTietHoaDon.Rows[i].Cells[2].Value);
                    dgvThemChiTietHoaDon.Rows[i].Cells[3].Value = dg * sl;
                    dem1 += Convert.ToDouble(dgvThemChiTietHoaDon.Rows[i].Cells[3].Value);
                    lblTongTien.Text = dem1.ToString();
                    lblSoTienBangChu.Text = DinhDang(ChuyenSo(lblTongTien.Text)) + " Đồng";
                }

            }
            else
            {
                MessageBox.Show("Không có dữ liệu để xóa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
           
        }
    }
}
